import { logout, getInfo } from '@/api/login'
import { getToken, setToken, setFullToken, getFullToken, removeToken, setSessionId, removeSession } from '@/utils/auth'
import Cookies from 'js-cookie'

const user = {
  state: {
    token: getToken(),
    name: '',
    roles: [],
    roleName: JSON.parse(sessionStorage.getItem('userInfo'))?.roleName || '',
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SetRoleName: (state, roleName) => {
      state.roleName = roleName || JSON.parse(sessionStorage.getItem('userInfo'))?.roleName
      sessionStorage.setItem('roleName', state.roleName)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        if (window.loginType == 'UM') {
          Cookies.remove('HKTOKEN')
        }
        getInfo()
          .then((res) => {
            const { userInfo, tokenInfo } = res
            if (userInfo.roleCodes && userInfo.roleCodes.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', userInfo.roleCodes)
              commit('SET_PERMISSIONS', userInfo.permissionCodes)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_NAME', userInfo.username)
            if (!getFullToken()) {
              setFullToken(tokenInfo)
              setSessionId(tokenInfo.sid)
            }
            resolve(res)
          })
          .catch((error) => {
            console.log(error)
            reject(error)
          })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.name)
          .then(() => {
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            removeToken()
            removeSession()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  }
}

export default user
